package models

import (
	"context"
	"errors"

	"gorm.io/gorm"
)

type Role struct {
	Model
	RoleName *string `json:"roleName" gorm:"column:role_name" binding:"required"` // 角色名称
	Status   *int    `json:"status" gorm:"column:status" binding:"required"`      //
	RoleKey  *string `json:"roleKey" gorm:"column:role_key" binding:"required"`   //角色代码

	Params  string           `json:"params" gorm:"-"`
	MenuIds []map[string]int `json:"menuIds" gorm:"-"`
}

func (Role) TableName() string {
	return "role"
}

//根据id获取角色
func GetRoleByID(ctx context.Context, id int64) (*Role, error) {
	role := new(Role)
	res := db(ctx).Table(role.TableName()).Where("id = ?", id).First(role)
	return role, checkErr(res.Error)
}

//获取角色列表
func GetRoleList(ctx context.Context, pageSize, pageIndex int) (map[string]interface{}, error) {
	data := map[string]interface{}{
		"count":     0,
		"list":      []*Role{},
		"pageIndex": pageIndex,
		"pageSize":  pageSize,
	}
	total := new(int64)
	db := db(ctx).Table("role")
	if res := db.Count(total); res.Error != nil {
		return data, res.Error
	}
	if *total <= 0 {
		return data, nil
	}
	data["count"] = total
	var roles []*Role
	res := db.Order("created_at desc").Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&roles)
	if res.Error != nil {
		return data, res.Error
	}
	data["list"] = roles
	return data, nil
}

//添加角色
func AddRole(tx *gorm.DB, r *Role) (int64, error) {
	exist := new(int64)
	res := tx.Table(`role`).
		Where("`role_name` = ? or `role_key` = ?", *r.RoleName, *r.RoleKey).
		Count(exist)
	if res.Error != nil {
		return 0, res.Error
	}
	if *exist > 0 {
		return 0, errors.New("角色name或角色key以存在，请换一个")
	}
	res = tx.Create(r)
	return int64(r.ID), res.Error
}

//修改角色信息
func UpdateRole(tx *gorm.DB, r *Role) error {
	existRole, err := GetRoleByID(baseCtx, int64(r.ID))
	if err != nil {
		return err
	}
	if r.RoleName != existRole.RoleName {
		return errors.New("角色名称不允许修改！")
	}
	if r.RoleKey != existRole.RoleKey {
		return errors.New("角色标识不允许修改！")
	}
	res := tx.Table("role").Where("id = ?", r.ID).Update("status", r.Status)
	return res.Error
}

func DeleteRoleByID(tx *gorm.DB, id int64) (err error) {
	return tx.Table("role").Where("id = ?", id).Delete(&Role{}).Error
}

func GetSimpleRoleList(ctx context.Context) ([]Role, error) {
	var roles []Role
	res := db(ctx).Table("role").Select("id,role_name,role_key").Find(&roles)
	return roles, res.Error
}
